const app = getApp()

Page({
  data: {
    myBestScore: 0,
    myRank: 0,
    rankingList: [],
    loading: true
  },

  onLoad() {
    this.loadRankingData()
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.loadRankingData()
  },

  // 加载排行榜数据（从云端获取）
  loadRankingData() {
    this.setData({ loading: true })
    
    wx.cloud.callFunction({
      name: 'getRanking',
      data: {
        limit: 50 // 获取前50名
      },
      success: res => {
        console.log('[云函数] [getRanking] 调用成功', res)
        if (res.result.success) {
          this.setData({
            rankingList: res.result.rankingList,
            myRank: res.result.myRank,
            myBestScore: res.result.myBestScore,
            loading: false
          })
          
          // 更新全局最佳分数
          app.globalData.bestScore = res.result.myBestScore
          wx.setStorageSync('bestScore', res.result.myBestScore)
        } else {
          this.loadLocalData()
        }
      },
      fail: err => {
        console.error('[云函数] [getRanking] 调用失败', err)
        this.loadLocalData()
        wx.showToast({
          title: '网络异常，显示本地数据',
          icon: 'none'
        })
      }
    })
  },

  // 加载本地数据作为备用
  loadLocalData() {
    const bestScore = wx.getStorageSync('bestScore') || 0
    this.setData({
      myBestScore: bestScore,
      myRank: bestScore > 0 ? 1 : 0,
      rankingList: bestScore > 0 ? [{
        nickname: '我',
        avatarUrl: '',
        score: bestScore,
        isCurrentUser: true
      }] : [],
      loading: false
    })
  },

  // 开始游戏
  startGame() {
    wx.vibrateShort()
    wx.navigateTo({
      url: '/pages/game/game'
    })
  },

  // 分享排行榜
  shareRanking() {
    wx.vibrateShort()
    
    const shareText = `我在"必须反着做"游戏中获得了${this.data.myBestScore}分！`
    
    wx.setClipboardData({
      data: shareText,
      success: () => {
        wx.showToast({
          title: '分享内容已复制',
          icon: 'success'
        })
      }
    })
  },

  // 刷新排行榜
  onPullDownRefresh() {
    this.loadRankingData()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  }
}) 